/**
 * com.monte.persistence.command.MyBatisPaginationQueryCommand.java
 * create by FengMy from 2013
 */
package com.monte.persistence.command;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.RowBounds;

import com.monte.common.Pagination;
import com.monte.mybatis.interceptor.ExecutorInterceptor;
import com.monte.persistence.CommandContext;
import com.monte.persistence.PersistenceCommand;
import com.monte.util.StringUtils;

/**
 * @描述:MyBatis分页查询命令
 * @author FengMy
 * @since 2013-3-20
 */
public class MyBatisPaginationQueryCommand<T> implements PersistenceCommand {
	private String mapper;
	private Pagination<T> pagination;
	private Object param;
	public MyBatisPaginationQueryCommand(String mapper,Pagination<T> pagination,Object param){
		if(StringUtils.isEmpty(mapper)){
			throw new IllegalArgumentException("mapper could not to be empty");
		}
		if(pagination==null){
			throw new IllegalArgumentException("pagination could not to be null");
		}
		this.mapper = mapper;
		this.pagination = pagination;
		this.param = param;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object execute(CommandContext context) {
		MappedStatement state = null;
		try{
			state = context.getSqlSession().getConfiguration().getMappedStatement(mapper+"Count");
		}catch(IllegalArgumentException e){
			//如果没有找到相应的mapper，会抛异常。这里不作处理
		}
		int count = 0;
		if(state == null){
			count =  (Integer) context.getSqlSession().selectOne(mapper, new ExecutorInterceptor.CountParameter(param));
		}
		count = (Integer) context.getSqlSession().selectOne(mapper + "Count", param);
		pagination.setRecordCount(count);
		List<T> list;
		if(count > 0){
			list = context.getSqlSession().selectList(mapper, param, new RowBounds((pagination.getCurrentPage() - 1) * pagination.getPageSize(), pagination.getPageSize()));
		}else{
			list = new ArrayList<T>();
		}
		pagination.setItems(list);
		return pagination;
	}

}
